package com.mine.controller;

import com.alibaba.fastjson.JSONArray;
import com.mine.config.VerifyCodeUtils;
import com.mine.pojo.Cart;
import com.mine.pojo.Meal;
import com.mine.pojo.User;
import com.mine.service.MealService;
import com.mine.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.mail.MessagingException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    MealService mealService;
    //*首页
    @RequestMapping("index")
    public String index(Model model){
        List<Meal> meals = mealService.queryAllMeal();//卖出最多的商品
        List<Meal> meals1 = mealService.queryBargainpriceMeal();//价钱最实惠（现价-原价）
        List<Cart> carts = mealService.querynewTitle();//最新评价
        try{
            if(meals.size() >= 3){
                List<Meal> mealList = meals.subList(0,3);
                model.addAttribute("mealList",mealList);
            }
            if(meals1.size() >= 3){
                List<Meal> mealList1 = meals1.subList(0,3);
                model.addAttribute("mealList1",mealList1);
            }
            if(carts.size() >= 2) {
                List<Cart> cartList = carts.subList(0, 2);
                model.addAttribute("cartList", cartList);
            }
        }catch (Exception e){
            System.out.println("菜单不少于3项");
            e.getStackTrace();
        }
        return "index";
    }

    //*登录页面
    @RequestMapping({"/","login"})
    public String loginCount(){
        return "login";
    }

    //*登录及验证
    @RequestMapping("/user/login")
    public String login(User user, Model model,HttpSession session){
        User user1 = userService.getUserByName(user.getUsername());
        if(user1!=null && user1.getPassword().equals(user.getPassword())){
            session.setAttribute("user",user1);//保存用户信息
            if(user1.getIsadmin().equals("0")){
                return "redirect:/index";
            }else {
                return "redirect:/admin/mealList";
            }

        }else{
            //如果错误就传msg信息到前台
            model.addAttribute("msg","用户名或密码错误");
            return "login";
        }
    }

    //*注销
    @RequestMapping("/user/logout")
    public String loginOut(HttpSession session){
        session.invalidate();
        return "redirect:/index";
    }

    //*注册页面
    @GetMapping("/register")
    public String register(Model model){
        model.addAttribute("user1",new User());
        return "register";
    }
    @PostMapping("/user/register")
    public String register(User user, String code,Model model, HttpSession session){
        String codes = (String) session.getAttribute("code");
        if(!code.equals(codes)){
            model.addAttribute("msg","验证码错误");
            model.addAttribute("user1",user);//将刚刚提交的信息返回到前端
            return "register";
        }
        User user1 = userService.getUserByName(user.getUsername());
        if(user1!=null) {  //用户名已存在，重新返回注册页面
            model.addAttribute("msg","用户名已存在");
            model.addAttribute("user1",user);//将刚刚提交的信息返回到前端
            return "register";
        }
        userService.addUser(user);
        return "redirect:/index";
    }
    //*验证码
    @RequestMapping("/getImage")
    public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
        //生成验证码
        String securityCode = VerifyCodeUtils.getSecurityCode();
        //将验证码放入session
        session.setAttribute("code", securityCode);
        System.out.println("===登录验证码===" + securityCode + "========");
        //生成图片
        BufferedImage image = VerifyCodeUtils.createImage(securityCode);
        //输出图片
        ServletOutputStream outputStream = response.getOutputStream();
        //调用工具类
        ImageIO.write(image, "png", outputStream);
    }
    //*忘记密码
    @RequestMapping("/forget")
    public String forget(){
        return "forget";
    }
    //*登录验证信息
    //根据用户名查询出来信息自动填充姓名邮箱
    @GetMapping(value = "verification",produces="text/html;charset=UTF-8")
    @ResponseBody
    public String verification(User user) {
        User user1 = userService.verification(user);
        if (user1 != null) {
            String data = JSONArray.toJSONString(user1);
            return data;
        }
        return "Fail";
    }
    //*获取邮件验证码
    @PostMapping("/verifeCode")
    @ResponseBody
    public String verifeCode(User user, HttpSession session) throws MessagingException {
        Integer num = userService.verifeCode(user);
        if (num > 0) {
            session.setAttribute(user.getUsername() + "code", num.toString());
            System.out.println("-------邮箱验证码-----" + num.toString());
            return "OK";
        }
        return "Fail";
    }
    //*发送验证码,修改密码
    @PostMapping("/user/verify")
    @ResponseBody
    public String verify(User user, String code, HttpSession session){
        System.out.println(user+"================"+code);
        String userCode = (String) session.getAttribute(user.getUsername() + "code");
        if (userCode != null && !"".equals(userCode) && userCode.equals(code)) {
            userService.modifyUserPassword(user);
            session.removeAttribute(user.getUsername() + "code");
            return "OK";
        }
        return "Fail";
    }

    //*关于我们界面
    @GetMapping("about")
    public String about(Model model){
        List<Meal> meals = mealService.queryAllMeal();//卖出最多的商品
        List<Meal> mealList1 = meals.subList(0, 2);
        model.addAttribute("mealList", mealList1);
        return "other/about";
    }
}
